package com.geralt.im.gui;

import java.awt.Color;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JPasswordField;

public class PasswordWithHint extends JPasswordField implements FocusListener {
	private String hint;
	private boolean showingHint;

	public PasswordWithHint() {
		super();
	}

	public PasswordWithHint(String hint) {
		super();
		super.setEchoChar((char) 0);
		super.setForeground(Color.gray);
		super.setText(hint);
		this.hint = hint;
		this.showingHint = true;
		super.addFocusListener(this);

	}

	@Override
	public void focusGained(FocusEvent e) {
		if (this.getPassword().length == 0) {
			super.setText("");
			super.setEchoChar('*');
			super.setForeground(Color.black);
			showingHint = false;
		}
	}

	@Override
	public void focusLost(FocusEvent e) {
		if (this.getPassword().length == 0) {
			super.setEchoChar((char) 0);
			super.setText(hint);
			super.setForeground(Color.gray);
			showingHint = true;
		}
	}

	@Override
	public char[] getPassword() {
		return showingHint ? new char[0] : super.getPassword();
	}

	@Override
	public void setText(String t) {
		if (t != null && !"".equals(t)) {
			this.showingHint = false;
		}
		super.setText(t);
	}
}
